import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { feeAdd, feeType, building, houses } from '../../apis/liveFee';
import { Button, Modal, Form, Input, Select, Cascader, Radio, message, Table, Pagination, DatePicker, Space } from 'antd';
import type { RadioChangeEvent } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import type { ColumnsType } from 'antd/es/table';
import '../../assets/scss/fee/feeAdd.scss'
import { AddType } from '../../apis/liveFee/type'
import { useLocation } from "react-router-dom"

const { Option } = Select;
const { SHOW_CHILD } = Cascader;
const layout = {
  labelCol: { span: 6 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};
const { RangePicker } = DatePicker;
// ---------------------------------------------------------------------------------------------
const FeeAdd = (): JSX.Element => {

  const navigate = useNavigate()
  const [type, setfeeType] = useState([])
  const [buildingList, setBuildingList] = useState([])
  const [show, setShow] = useState(false)
  const [addData, setAddData] = useState({
    id: 0,
    begindate: '',
    enddate: '',
    buildingid: 0,
    houseids: []
  })

  const [form] = Form.useForm();
  const onGenderChange = (value: string) => {
    switch (value) {
      case 'male':
        form.setFieldsValue({ note: 'Hi, man!' });
        break;
      case 'female':
        form.setFieldsValue({ note: 'Hi, lady!' });
        break;
      case 'other':
        form.setFieldsValue({ note: 'Hi there!' });
        break;
      default:
    }
  };
  // 添加确定
  const onFinish = (values: any) => {
    console.log({ ...addData, ...values, buildingid: values.buildingid.pop() });
    Add({ ...addData, ...values, buildingid: values.buildingid.pop() })
  };

  const onReset = () => {
    form.resetFields();
  };

  // const onFill = () => {
  //   form.setFieldsValue({ note: 'Hello world!', gender: 'male' });
  // };

  // 级联选择器
  interface Option {
    value: string | number;
    label: string;
    children?: Option[];
  }
  const options: Option[] = buildingList
  const onChange: any = (value: number[]) => {
    setListData({ ...listData, buildingid: value.slice(-1)[0] })
  };

  //单选 
  const [value, setValue] = useState(0);
  const onChange1 = (e: RadioChangeEvent) => {
    if (e.target.value === 1) {
      console.log('全部');
      if (!listData.buildingid) {
        message.open({
          type: 'error',
          content: '请先选择楼栋',
        });
        setValue(0)
      } else {
        const ids = roomList.map((item: any) => item.id)
        console.log(ids);
        form.setFieldsValue({ houseids: ids });
        setAddData({ ...addData, houseids: [] })
        setShow(false);
      }
    } else {
      console.log('部分');
      if (!listData.buildingid) {
        message.open({
          type: 'error',
          content: '请先选择楼栋',
        });
        setValue(0)
      } else {
        setShow(true);
        form.setFieldsValue({ houseids: [] });
      }
    }
    setValue(e.target.value);
  };

  // -----------------------------------------------

  const handleOk = () => {
    // setIsModalOpen();
    onRoom()
    setShow(false);
  };

  const handleCancel = () => {
    // setIsModalOpen(false);
    setShow(false);
  };
  // ------------------------------------------------
  // 房间表格
  const [roomList, setRoomList] = useState([]);
  interface DataType {
    key: string;
    name: string;
    age: number;
    address: string;
    id: number;
    tags: string[];
  }
  const data: DataType[] = roomList;
  const columns: ColumnsType<DataType> = [
    {
      title: '楼号',
      dataIndex: 'id',
      // key: 'housenod',
      align: 'center'
    },
    {
      title: '房间号',
      dataIndex: 'houseno',
      // key: 'houseno',
      align: 'center'
    },
    {
      title: '业主',
      dataIndex: 'building',
      // key: 'building',
      align: 'center'
    }, {
      title: '电话',
      dataIndex: 'iii',
      // key: 'houseno',
      align: 'center'
    }
  ];

  const [roomData, setRoomData] = useState([]);
  const roomColumns: ColumnsType<DataType> = [
    {
      title: '楼号',
      dataIndex: 'id',
      align: 'center'
    },
    {
      title: '房间号',
      dataIndex: 'houseno',
      align: 'center'
    },
    {
      title: '操作',
      align: 'center',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" danger onClick={() => roomDel(record.id)}>删除</Button>
        </Space>
      )
    }
  ];

  // 房间删除---------------------------------------
  const roomDel = (id: number) => {
    roomData.forEach((item: any, index, data) => {
      if (item.id == id) {
        data.splice(index, 1)
        setRoomData([...data])
      } else {
      }
    })
  }
  const roomIds = () => {
    // console.log(roomData.map((item: any) => item.id));
    const houseids: any = roomData.map((item: any) => item.id)
    setAddData({ ...addData, houseids })
  }

  // const roomDel = (id: number) => {
  //   const data = roomData
  //   console.log(data);
  //   let idx = data.findIndex(e => e.id === id)
  //   console.log(idx);
  //   data.splice(idx,1)
  //   setRoomData([...data])
  // }
  // ---------------------------------------

  // 分页
  const [counts, setCounts] = useState(0);
  const [listData, setListData] = useState({
    page: 1,//页
    psize: 10,//条
    buildingid: 0,
    houseno: ''
  });
  const onPagination = (page: number, psize: number) => {
    // console.log(page, psize);
    setListData({ ...listData, psize, page });
  }

  // 日期选择
  const onRangeChange = (dates: null | (Dayjs | null)[], dateStrings: string[]) => {
    if (dates) {
      // console.log(dateStrings[0], 'to', dateStrings[1]);
      setAddData({ ...addData, begindate: dateStrings[0], enddate: dateStrings[1], })
    } else {
      // console.log('Clear');
    }
  };
  const rangePresets: {
    label: string;
    value: [Dayjs, Dayjs];
  }[] = [
      { label: '最近一周', value: [dayjs().add(-7, 'd'), dayjs()] },
      { label: '最近一个月', value: [dayjs().add(-30, 'd'), dayjs()] },
      { label: '最近三个月', value: [dayjs().add(-90, 'd'), dayjs()] },
    ];

  // 房间列表查询-------------------------------------------------
  const [roomForm] = Form.useForm();
  const onRoomFinish = (values: any) => {
    console.log(values);
    const { buildingid, houseno } = values
    setListData({ ...listData, buildingid, houseno })
  };

  const roomFill = () => {
    roomForm.setFieldsValue({ buildingid: listData.buildingid });
  };

  // 房间表格复选
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const onRoomChange = (houseno: any) => {
    setSelectedRowKeys(houseno);
  };
  const roomSelection = { selectedRowKeys, onChange: onRoomChange };

  // 房间确定按钮
  const onRoom = () => {
    // setAddData({ ...addData, houseids: selectedRowKeys })
    // form.setFieldsValue({ houseids: selectedRowKeys });
    setRoomData(selectedRowKeys)
    setShow(false);
  }

  // 费用类型接口----------------------------------------------------
  const getFeeType = async () => {
    const res: any = await feeType();
    // console.log(res.data.list);
    if (res && res.errCode === 10000) {
      setfeeType(res.data.list)
    } else {
      message.open({
        type: 'error',
        content: '数据加载错误!!!',
      });
    }
  }
  // 楼栋接口
  const getBuilding = async () => {
    const res: any = await building();
    // console.log(res.data.list);
    if (res && res.errCode === 10000) {
      setBuildingList(res.data.list)
    } else {
      message.open({
        type: 'error',
        content: '数据加载错误!!!',
      });
    }
  }
  // 房间接口
  const getHouses = async () => {
    const res: any = await houses(listData);
    // console.log(res);
    if (res && res.errCode === 10000) {
      setRoomList(res.data.list)
      setCounts(res.data.counts)
    } else {
      message.open({
        type: 'error',
        content: '数据加载错误!!!',
      });
    }
  }

  // 添加接口
  const { state: { id } } = useLocation();
  const alterID = () => {
    setAddData({ ...addData, id })
    // console.log(id);
  }
  const Add = async (val: AddType) => {
    const res: any = await feeAdd(val);
    // console.log(res);
    if (res && res.errCode === 10000) {
      setfeeType(res.data.list)
      navigate('/home/fee')
      message.open({
        type: 'success',
        content: '添加成功',
      });
    } else {
      message.open({
        type: 'error',
        content: '数据添加异常!!!',
      });
    }
  }

  useEffect(() => {
    getFeeType();
    getBuilding();
    alterID();
  }, [])
  useEffect(() => {
    getHouses();
    roomFill();
  }, [listData])
  useEffect(() => {
    roomIds();
  }, [roomData])


  return (
    <div className='fee_add'>
      <div className='title'>缴费添加</div>
      <div className='add_form'>
        <Form
          {...layout}
          form={form}
          name="control-hooks"
          onFinish={onFinish}
          style={{ maxWidth: 400 }}
        >
          <Form.Item name="type" label="费用类型">
            <Select
              placeholder="请选择"
              onChange={onGenderChange}
              allowClear
            >
              {type.map((item: any) => (
                <Option key={item.id} value={item.name}>{item.name}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="price" label="金额">
            <Input />
          </Form.Item>
          <Form.Item label="账期">
            <Space direction="vertical" size={12}>
              <RangePicker format="YYYY-MM-DD HH:mm:ss" presets={rangePresets} onChange={onRangeChange} />
            </Space>
          </Form.Item>
          <Form.Item name="buildingid" label="小区">
            <Cascader showCheckedStrategy={SHOW_CHILD} fieldNames={{ label: 'name', value: 'id', children: 'children' }} options={options} onChange={onChange} placeholder="请选择" />
          </Form.Item>
          <Form.Item label="缴费房间">
            <Radio.Group onChange={onChange1} value={value}>
              <Radio value={1}>全部</Radio>
              <Radio value={2}>部分房间</Radio>
            </Radio.Group>
          </Form.Item>
          {/* <Form.Item name="houseids" label="备注">
            <Input.TextArea rows={2} />
          </Form.Item> */}
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
          >
            {({ getFieldValue }) =>
              getFieldValue('gender') === 'other' ? (
                <Form.Item name="customizeGender" label="Customize Gender" rules={[{ required: true }]}>
                  <Input />
                </Form.Item>
              ) : null
            }
          </Form.Item>
          <Form.Item>
            {
              (() => {
                if (!show) {
                  return <div className='add_tab'>
                    <Table columns={roomColumns} dataSource={roomData} pagination={false} />
                  </div>
                }
                else {
                  return
                }
              })()
            }
          </Form.Item>
          < Form.Item {...tailLayout} className='add_btn'>
            <Button type="primary" htmlType="submit" size='large'>
              确定
            </Button>
            <Button htmlType="button" onClick={onReset} size='large' className='onReset'>
              重置
            </Button>
          </ Form.Item>
        </Form>
      </div >
      {
        (() => {
          if (show) {
            return <Modal className='modal' title="房间" width={800} open={true} onOk={handleOk} onCancel={handleCancel}>
              <div className='tab'>
                <Form
                  // {...layout}
                  form={roomForm}
                  onFinish={onRoomFinish}
                  style={{ maxWidth: 800, display: "flex", justifyContent: "space-evenly" }}
                  className='form'
                >
                  <Form.Item name="houseno" label="房间号">
                    <Input />
                  </Form.Item>
                  <Form.Item name="buildingid" label="小区名称">
                    <Input />
                  </Form.Item>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
                  >
                    {({ getFieldValue }) =>
                      getFieldValue('gender') === 'other' ? (
                        <Form.Item name="customizeGender" label="Customize Gender" rules={[{ required: true }]}>
                          <Input />
                        </Form.Item>
                      ) : null
                    }
                  </Form.Item>
                  <Form.Item {...tailLayout}>
                    <Button type="primary" htmlType="submit">
                      查询
                    </Button>
                  </Form.Item>
                </Form>
                <Table rowSelection={{
                  type: 'checkbox',
                  ...roomSelection,
                }} rowKey={(record: any) => record} columns={columns} dataSource={data} pagination={false} />
                <div className='paging'>
                  <Pagination
                    total={counts}
                    showTotal={(total) => `共 ${total} 条`}
                    pageSizeOptions={[10, 15, 20, 30]}
                    defaultPageSize={10}
                    current={listData.page}
                    showSizeChanger={true}
                    onChange={onPagination}
                  />
                </div>
                {/* <div>
                  <Button type="primary" onClick={onRoom} size='large'>确定</Button>
                </div> */}
              </div>
            </Modal>
          }
          else {
            return
          }
        })()
      }
    </div >
  )
}
export default FeeAdd;